package top.riske.gen3d.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.riske.gen3d.http.response.Result;


import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应工具类
 * created by vital on 2025/3/2 下午1:55
 */
public class ResponseUtils {

    private static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

    // json解析工具
    private static final ObjectMapper objectMapper= new ObjectMapper();

    /**
     * 设置错误响应结果
     */
    public static void setErrorResponse(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Result result) throws IOException {
        log.error("{};{}{}",result.getTimestamp(),result.getMessage(), RequestUtils.getRequestInfo(httpRequest));
        // 设置响应内容类型为JSON
        httpResponse.setContentType("application/json");
        httpResponse.setCharacterEncoding("UTF-8");

        // 获取输出流并写入JSON数据
        try (PrintWriter out = httpResponse.getWriter()) {
            String jsonResponse = objectMapper.writeValueAsString(result);
            out.print(jsonResponse);
            out.flush();
        }
    }

}
